<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <link rel="stylesheet" href="/css/element.css">
    <link rel="stylesheet" href="/editor/css/style.css" />
    <link rel="stylesheet" href="/editor/css/editormd.css" />
    <script src="/editor/js/jquery.min.js"></script>
    <script src="/editor/js/editormd.min.js"></script>
    <#include "/include/commonjs.html">
    <title>内容新建</title>
</head>
<body>
<div id="app">
    <#include "/include/daohang.html">
    <div style="background-color: white;padding: 20px;border-radius: 15px">

        <div style="padding: 20px">
            <el-form :model="form"  label-width="60px" class="demo-ruleForm" :rules="rules" ref="form">
                <el-row>
                    <el-col :span="20">
                            <el-form-item label="标题: " prop="title">
                                <el-input placeholder="请输入标题" v-model="form.title" />
                            </el-form-item>
                    </el-col>
                    <el-col :span="4">
                        <el-button type="primary" @click="submitFrom('form')">提交</el-button>
                    </el-col>
                </el-row>

                <el-row>
                    <el-col :span="10">
                        <el-form-item label="标签: " prop="tags" >
                            <el-input placeholder="请输入标签" v-model="form.tags"></el-input>
                        </el-form-item>
                    </el-col>
                    <el-col :span="10">
                        <el-form-item label="栏目: " prop="channelId" >
                            <el-cascader
                                    v-model="form.channelId"
                                    :options="data"
                                    :props="props"
                                    style="width: 100%"
                                    :clearable="true"
                                    @change="handleChange_channel">
                            </el-cascader>
                        </el-form-item>
                    </el-col>
                </el-row>
            </el-form>
            <br>

            <div id="test-editormd" style="padding: 20px">
                <textarea id="content-main"  style="display:none;">
                </textarea>
            </div>
            <br><br>
        </div>
    </div>
</div>

<script type="text/javascript">
    var testEditor;

    var Main = {
        extends: global,
        data() {
            return{
                activeIndex: '2',
                activeIndex2: '2',
                form:{
                    channelId:${channelId}
                },
                formLabelWidth:'120px',
                restaurants: [],
                state: '',
                select: '',
                data: [],
                props:{
                    children: 'childs',
                    label: 'channelname',
                    value:'id',
                    checkStrictly:true,
                    emitPath:false
                },
                rules: {
                    title: [
                        {required: true, message: '请输入标题', trigger: 'blur'},
                        {min: 1, max: 50, message: '长度在 1 到 50 个字符', trigger: 'blur'}
                    ],
                    tags: [
                        {required: true, message: '请输入标签', trigger: 'blur'},
                        {min: 1, max: 50, message: '长度在 1 到 50 个字符', trigger: 'blur'}
                    ],
                    channelId:[
                        {required: true, message: '请选择栏目id', trigger: 'blur'},
                    ],
                }
            }
        },
        created(){
            this.getChannel()
        },
        methods: {
            getChannel(){
                api.GET('/channel/getallchannel',null,(res)=>{
                    if(res.code===0){
                        this.data=res.data;
                    }
                })
            },
            handleChange_channel(val){
                this.form.channelId=val;
            },
            submitFrom(formName){
                console.log(JSON.stringify(this.form))
                this.$refs[formName].validate((valid) => {
                    if (valid) {
                        //获取富文本
                        var content=$("#content-main").val();
                        var data={'title':this.form.title,'content':content,'tag':this.form.tags,'channelId':this.form.channelId,'isPrivate':false};
                        api.POST('/note/save',data,(result)=>{
                            if (result.code==0){
                                this.$message({
                                    showClose: true,
                                    message: '添加成功',
                                    type: 'success'
                                });
                                  window.location.href="/update?id="+result.data
                            }
                        })
                    } else {
                        console.log('error submit!!');
                        return false;
                    }
                });

            },
            handleSelect(key, keyPath) {
                console.log(key, keyPath);
            },
        }
    }
    var Ctor = Vue.extend(Main)
    new Ctor().$mount('#app')


    function initPasteDragImg(Editor){
        var doc = document.getElementById(Editor.id)
        doc.addEventListener('paste', function (event) {
            var items = (event.clipboardData || window.clipboardData).items;
            var file = null;
            console.log(items)
            console.log(items.length)
            if (items && items.length) {
                // 搜索剪切板items
                for (var i = 0; i < items.length; i++) {
                    if (items[i].type.indexOf('image') !== -1) {
                        file = items[i].getAsFile();
                        break;
                    }
                }
            }
            else {
                console.log("当前浏览器不支持");
                return;
            }
            if (!file) {
                console.log("粘贴内容非图片");
                return;
            }
            uploadImg(file,Editor);
        });
        var dashboard = document.getElementById(Editor.id)
        dashboard.addEventListener("dragover", function (e) {
            e.preventDefault()
            e.stopPropagation()
        })
        dashboard.addEventListener("dragenter", function (e) {
            e.preventDefault()
            e.stopPropagation()
        })
        dashboard.addEventListener("drop", function (e) {
            e.preventDefault()
            e.stopPropagation()
            var files = this.files || e.dataTransfer.files;
            uploadImg(files[0],Editor);
        })
    }
    function uploadImg(file,Editor){
        var formData = new FormData();
        var fileName=new Date().getTime()+"."+file.name.split(".").pop();
        formData.append('editormd-image-file', file, fileName);
        $.ajax({
            url: Editor.settings.imageUploadURL,
            type: 'post',
            data: formData,
            processData: false,
            contentType: false,
            dataType: 'json',
            success: function (msg) {
                var success=msg['success'];
                if(success==1){
                    var url=msg["url"];
                    if(/\.(png|jpg|jpeg|gif|bmp|ico)$/.test(url)){
                        Editor.insertValue("![]("+msg["url"]+")");
                    }else{
                        Editor.insertValue("[下载附件]("+msg["url"]+")");
                    }
                }else{
                    console.log(msg);
                    alert("上传失败");
                }
            }
        });
    }

    $(function() {
        testEditor = editormd("test-editormd", {
            imageDrop: true,  // 开启图片拖拽上传功能
            width   : "100%",
            height  : 640,
            syncScrolling : "single",
            path    : "/editor/lib/",
            saveHTMLToTextarea : true ,// 保存 HTML 到 Textarea
            htmlDecode: "style,script,iframe",
            imageUpload : true,  //开启图片上传
            imageFormats : ["jpg", "jpeg", "gif", "png", "bmp", "webp"],
            imageUploadURL : "/filebase64/uploadimage", //上传的路径，就是mvc的controller路径
            onload : function() {
                initPasteDragImg(this); //允许粘贴和拖拉图片到editormd
            }
        });
    });



</script>
</body>
</html>
